class EgraphController < ApplicationController
  require 'scruffy'
  def histogram_action
    if eaction = Eaction.find(params[:id], :include => [:eapp])
      if eload = Eload.find(:first, :conditions => ["eapp_id=? and active=1",eaction.eapp.id])
        eaction = Eaction.find(:first, :include => [:erequests,:eapp], :conditions => ["eactions.id=? and erequests.happened_at>eapps.start_on and erequests.happened_at<eapps.end_on and erequests.eload_id=?",params[:id],eload.id])
      else
        eaction = Eaction.find(params[:id], :include => [:erequests,:eapp], :conditions => ["erequests.happened_at>eapps.start_on and erequests.happened_at<eapps.end_on"])
      end
      times = Array.new
      times = eaction.erequests.collect{|erequest| erequest.time} if eaction
      eaction = Eaction.find(params[:id], :include => [:eapp])
      histogram(times, :title => eaction.title.titlecase, :subtitle => "Time")
    end
  end
  def histogram(numbers, *args)
    numbers = numbers.remove_outliers
    args = args[0]
    min = numbers.min
    max = numbers.max
    bins = 5
    width = (max.to_f-min.to_f)/((bins-1).to_f)
    width = 1 if width==0
    data = Array.new(bins,0)
    for n in numbers
      data[((n-min)/width).to_i] += 1
    end
    graph = Scruffy::Graph.new
    graph.theme = Scruffy::Themes::Base.new(:background => ['#fff', '#fff'], :marker => '#000', :colors => ['#900'])
    graph.title = args[:title]
    graph.add :bar, args[:subtitle], data
    graph.point_markers = (0..bins).collect{|i| min+i*width} unless numbers.length==0
    g = graph.render(:width => 400, :as => 'JPG', :min_value => 0)
    send_data g, :type => 'image/jpeg', :disposition => 'inline'
  end
end
